import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { Modal, Form, Input } from 'antd'

const FormItem = Form.Item

const normalFn = () => {
}

@Form.create()
export default class MyModal extends Component {
  static propTypes = {
    data: PropTypes.array.isRequired,
    visible: PropTypes.bool.isRequired,
    form: PropTypes.object.isRequired,
    title: PropTypes.string,
    onOk: PropTypes.func,
    onCancel: PropTypes.func,
  }

  static defaultProps = {
    title: '编辑',
    onOk: normalFn,
    onCancel: normalFn,
  }

  handleSubmit = (e) => {
    e.preventDefault()
    const {form, onOk} = this.props
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        onOk(values)
      }
    })
  }

  renderFormItem = ({label, key, rules}) => {
    const {form} = this.props
    const {getFieldDecorator} = form
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    const message = `请输入${label}`
    return (
      <FormItem key={key} {...formItemLayout} label={label}>
        {getFieldDecorator(key, {
          rules: [rules || {
            required: true, message,
          }],
        })(
          <Input placeholder={message} />
        )}
      </FormItem>
    )
  }

  render() {
    const {title, onCancel, data, visible} = this.props
    return (
      <Modal
        visible={visible}
        title={title}
        onOk={this.handleSubmit}
        onCancel={onCancel}
      >
        <Form onSubmit={this.handleSubmit}>
          {data.map(item => this.renderFormItem(item))}
        </Form>
      </Modal>
    )
  }
}
